/*
 * Copyright ©2018 贾维程. All rights reserved.
 */

package org.handover.controller.handover;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.handover.domain.Handover;
import org.handover.repository.HandoverRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Controller
@RequestMapping("/handover/")
public class HandoverExport {
    @Autowired
    private HandoverRepository handoverRepository;

    @GetMapping("export")
    public String getExport(Model model) {
        LocalDate nowDate = LocalDate.now();
        model.addAttribute("nowYear", nowDate.getYear());
        model.addAttribute("nowWeek", nowDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR) - 2);
        return "/handover/export";
    }

    @PostMapping("export")
    public void postExport(Integer year, Integer week, HttpServletResponse response, Model model) throws Exception {

        LocalDate inputDate = LocalDate.of(year, 1, 1);
        ZoneId zone = ZoneId.systemDefault();

        inputDate = inputDate.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));
        inputDate = inputDate.plusWeeks(week - 1);
        //System.out.println(inputDate);
        //System.out.println(inputDate.plusDays(6));
        /* // 检查交接是否缺失
        for (int i=0; i<=6; i++){
            for (Shift shift : shiftRepository.findAll()){
                if (!handoverRepository.existsByDateAndShiftId(Date.from(inputDate.plusDays(i).atStartOfDay().atZone(zone).toInstant()),shift)){
                    model.addAttribute("message",inputDate +" "+shift.getName()+" 不存在");
                    LocalDate nowDate = LocalDate.now();
                    model.addAttribute("nowYear", nowDate.getYear());
                    model.addAttribute("nowMonth", nowDate.get(ChronoField.ALIGNED_WEEK_OF_YEAR)-2);
                    return "/handover/export";
                }
            }
        }
        */
        //Date date = Date.from(inputDate.atStartOfDay().atZone(zone).toInstant());

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yy");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("ST23大润发海城店" + dateTimeFormatter.format(inputDate) + "年第" + week + "周E.D.P工作交接记录.xls").getBytes(), "iso-8859-1"));
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:handover.xls")));


        /*
        //int i = workbook.getSheetIndex("xt"); // sheet表名
        //sheet = workbook.getSheetAt(i);
        HSSFRow row = sheet.getRow(1); // 获取指定的行对象，无数据则为空，需要创建

        if (row == null) {
            row = sheet.createRow(0); // 该行无数据，创建行对象
        }
        //Cell cell = row.createCell(0); // 创建指定单元格对象。如本身有数据会替换掉
        Cell cell = row.getCell(0);
        // 设置内容
        cell.setCellValue(" "+ new SimpleDateFormat("yyyy年MM月dd日").format(handover.getDate()) +"   星期二                                              "+ handover.getShiftId().getName() +"："+handover.getUserId().getName());
        */
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC, "date"));
        orders.add(new Sort.Order(Sort.Direction.ASC, "shiftId"));
        List<Handover> handoverList = handoverRepository.findAllByDateGreaterThanEqualAndDateLessThanEqual(Date.from(inputDate.atStartOfDay().atZone(zone).toInstant()), Date.from(inputDate.plusDays(6).atStartOfDay().atZone(zone).toInstant()), new Sort(orders));
        for (int j = 0; j < handoverList.size(); j++) {
            Integer titleRow = null, beginRow = null, beginNo = null;
            String timeString, beginString;
            Handover handover = handoverList.get(j);
            if (1 == handover.getShift().getId()) {
                titleRow = 1;
                beginRow = 5;
                beginNo = 3;
                timeString = "8:00-15:30 ";
                beginString = "           ";
            } else {
                titleRow = 17;
                beginRow = 20;
                beginNo = 2;
                timeString = "16:00-23:00 ";
                beginString = "            ";
            }
            HSSFSheet sheet = workbook.getSheetAt(j / 2);
            Date handoverDate = new SimpleDateFormat("yyyy-MM-dd").parse(handover.getDate().toString());
            sheet.getRow(titleRow).getCell(0).setCellValue(" " + new SimpleDateFormat("yyyy年MM月dd日").format(handover.getDate()) + "   " + handoverDate.toInstant().atZone(zone).toLocalDate().getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA) + "                                              " + handover.getShift().getName() + "：" + handover.getUser().getUserInformation().getName());
            sheet.getRow(titleRow + 1).getCell(0).setCellValue("                                            机房温度：" + handover.getTemperature() + "℃              机房湿度：" + handover.getHumidity() + "%");
            // 写入交接内容，死了好多脑细胞啊 o(╯□╰)o
            int correction = 0; //修正值，为了多字折行
            for (int i = 0; i < handover.getDetailsList().size(); i++) {
                String detail = handover.getDetailsList().get(i).getDetail();
                if (detail.length() > 38) {
                    sheet.getRow(i + beginRow + correction).getCell(0).setCellValue((0 == i ? timeString : beginString) + (i + beginNo) + "、" + detail.substring(0, 37));
                    correction++;
                    sheet.getRow(i + beginRow + correction).getCell(0).setCellValue(beginString + "   " + detail.substring(38));
                } else {
                    sheet.getRow(i + beginRow + correction).getCell(0).setCellValue((0 == i ? timeString : beginString) + (i + beginNo) + "、" + detail);
                }
            }
        }

        workbook.write(response.getOutputStream());
        workbook.close();
        //response.sendRedirect("/handover/list");
        //return "/handover/export";
    }

    @PostMapping("exportValidate")
    @ResponseBody
    public boolean exprotValidate(Integer year, Integer week) {
        LocalDate inputDate = LocalDate.of(year, 1, 1);
        ZoneId zone = ZoneId.systemDefault();

        inputDate = inputDate.with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));
        inputDate = inputDate.plusWeeks(week - 1);

        return handoverRepository.countByDateGreaterThanEqualAndDateLessThanEqual(Date.from(inputDate.atStartOfDay().atZone(zone).toInstant()), Date.from(inputDate.plusDays(6).atStartOfDay().atZone(zone).toInstant())) == 14 ? true : false;
    }

}
